package com.hmall.gateway.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author 16701
 */
@Slf4j
@Component
public class DemoGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径
        String uri = exchange.getRequest().getPath().toString();
        //如果是白名单的请求，直接放行
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(uri,excludePath)){
                return chain.filter(exchange);
            }
        }
        //鉴权
        //获取令牌
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
            //令牌为空，设置响应码401并返回
        if(token==null || "".equals(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return chain.filter(exchange);
        }
        Long userId;
        try {
            //令牌校验失败，设置响应码401并返回
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            log.error("认证失败！请先登录");
            return chain.filter(exchange);
        }
        //令牌有效，设置到请求头中，
        exchange.getRequest().mutate().header("user-info",userId.toString());

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
